<!--
 * @Descripttion: 查看考卷
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-05-19 14:50:40
 * @LastEditTime: 2021-05-21 00:21:10
 * @FilePath: \cscec-pms-admin\src\views\partyMasses\partyManage\examinationPlan\paper.vue
-->
<template>
  <base-breadcrumb class="UpdateStudyEduc-container">
    <a-spin :spinning="loading">
      <a-card :bordered="false">
        <title-name title="基础信息" />
        <custom-form
          ref="form"
          :is-validate="true"
          :edit-model="''"
          :form="form"
          :form-list="formOption"
        />
        <!-- 题型列表 -->
        <template v-for="({n,t,i},index1) in form.content">
          <div :key="index1">
            <title-name :title="n" />
            <!-- 单选题 -->
            <ul v-if="t===0">
              <!-- 题干 -->
              <li
                v-for="({n,s,e},index2) in i"
                :key="index2"
              >
                <p>{{ index2+1 }}.{{ n }}({{ s }}分)</p>
                <!-- 答案 -->
                <div class="paper-answer-list">
                  <div
                    v-for="(item,index3) in e"
                    :key="index3"
                    class="paper-answer-item"
                    @click="handleRadio(item,e)"
                  >
                    <a-radio
                      :disabled="pageType!=='exam'"
                      :checked="item.u===1"
                    />
                    <div class="paper-answer-item-wrapper">
                      <span>{{ item.o }}</span>
                      <b>.</b>
                      <span class="paper-answer-item-text">{{ item.c }}</span>
                    </div>
                  </div>
                </div>
                <!-- 答案 -->
                <!-- 结果 -->
                <p
                  v-if="form.state === 1 &&pageType!=='exam'"
                  class="paper-result"
                >
                  ( 回答结果: {{ result(t,e) }} | 正确答案 : {{ rightAnswers(t,e) }} )
                </p>
                <!-- 结果 -->
              </li>
              <!-- 题干 -->
            </ul>
            <!-- 单选题 -->
            <!-- 多选题 -->
            <ul v-if="t===1">
              <!-- 题干 -->
              <li
                v-for="({n,s,e},index2) in i"
                :key="index2"
              >
                <p>{{ index2+1 }}.{{ n }}({{ s }}分)</p>
                <!-- 答案 -->
                <div class="paper-answer-list">
                  <div
                    v-for="(item,index3) in e"
                    :key="index3"
                    class="paper-answer-item"
                    @click="handleCheckbox(item)"
                  >
                    <a-checkbox
                      :disabled="pageType!=='exam'"
                      :checked="item.u===1"
                    />
                    <div class="paper-answer-item-wrapper">
                      <span>{{ item.o }}</span><b>.</b><span class="paper-answer-item-text">{{ item.c }}</span>
                    </div>
                  </div>
                </div>
                <!-- 答案 -->
                <!-- 结果 -->
                <p
                  v-if="form.state === 1 &&pageType!=='exam'"
                  class="paper-result"
                >
                  ( 回答结果: {{ result(t,e) }} | 正确答案 : {{ rightAnswers(t,e) }} )
                </p>
                <!-- 结果 -->
              </li>
              <!-- 题干 -->
            </ul>
            <!-- 多选题 -->
            <!-- 判断题 -->
            <ul v-if="t===2">
              <!-- 题干 -->
              <li
                v-for="({n,s,e},index2) in i"
                :key="index2"
              >
                <p>{{ index2+1 }}.{{ n }}({{ s }}分)</p>
                <!-- 答案 -->
                <div class="paper-answer-list">
                  <div
                    v-for="(item,index3) in e"
                    :key="index3"
                    class="paper-answer-item"
                    @click="handleRadio(item,e)"
                  >
                    <a-radio
                      :disabled="pageType!=='exam'"
                      :checked="item.u===1"
                    />
                    <div class="paper-answer-item-wrapper">
                      <span class="paper-answer-item-text">{{ item.c }}</span>
                    </div>
                  </div>
                </div>
                <!-- 答案 -->
                <!-- 结果 -->
                <p
                  v-if="form.state === 1 &&pageType!=='exam'"
                  class="paper-result"
                >
                  ( 回答结果: {{ result(t,e) }} | 正确答案 : {{ rightAnswers(t,e) }} )
                </p>
                <!-- 结果 -->
              </li>
              <!-- 题干 -->
            </ul>
            <!-- 判断题 -->
            <!-- 问答题 -->
            <ul v-if="t==3">
              <!-- 题干 -->
              <li
                v-for="({n,s,w},index2) in i"
                :key="index2"
              >
                <p>{{ index2+1 }}.{{ n }}({{ s }}分)</p>
                <!-- 答案 -->
                <div class="paper-answer-textarea">
                  <base-textarea
                    :disabled="pageType!=='exam'"
                    :value="w"
                    placeholder="请输入"
                    :auto-size="{ minRows: 3, maxRows: 6 }"
                    @change="handleTextarea($event,i,index2)"
                  />
                </div>
                <!-- 答案 -->
              </li>
              <!-- 题干 -->
            </ul>
            <!-- 问答题 -->
          </div>
        </template>
        <!-- 题型列表 -->
      </a-card>
      <div class="tool-btns">
        <a-button
          v-if="pageType==='exam'"
          class="ml12"
          type="primary"
          :loading="loadingState.DRAFT"
          @click="handleSubmit('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="pageType==='exam'"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          class="ml12"
          type="default"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>
<script>
import {
  getExamUserPaperDetail,
  saveUserPaperDraft,
  submitUserPaper,
  startPlan
} from '@/api/partyMasses/partyManage/examinationPlan'
export default {
  name:'a'+ Date.now(),
  // name: 'Paper',
  components: {},
  data() {
    return {
      // 页面加载
      loading: false,
      // 页面类型
      pageType: '',
      // 表单
      form: {
        examPlanId: void 0,
        examPlanName: void 0,
        examPaperName: void 0,
        examTotalScore: 0,
        planStartTime: void 0,
        planEndTime: void 0,
        startTime: void 0,
        partyMemberName: void 0,
        score: 0
      },
      // 按钮loading
      loadingState: {
        DRAFT: false,
        SUBMITTED: false
      },
      // 考卷数据
      data: {}
    }
  },
  computed: {
    // 表单配置
    formOption() {
      return [
        {
          label: '考试计划名称',
          keyName: 'examPlanName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '考卷',
          keyName: 'examPaperName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '考卷总分',
          keyName: 'totalScore',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '计划开始时间',
          keyName: 'planStartTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '计划结束时间',
          keyName: 'planEndTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '考试人',
          keyName: 'partyMemberName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '参考时间',
          keyName: 'startTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '考试得分',
          keyName: 'score',
          type: 'BaseInput',
          disabled: true
        }
      ]
    }
  },
  created() {
    this.getData()
    this.isBegin()
  },
  methods: {
    /**
     * @description: 获取考卷数据
     * @param {Void}
     * @return {Void}
     */
    getData() {
      this.pageType = this.$route.query.pageType
      this.loading = true
      getExamUserPaperDetail({
        userId: this.$route.query.id,
        examPlanId: this.$route.query.examPlanId
      })
        .then(({ data }) => {
          this.form = data
        })
        .catch((error) => {
          console.log(error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 开始考试
     * @param {*}
     * @return {*}
     */
    isBegin() {
      if (this.pageType === 'exam') {
        startPlan({ id: this.$route.query.examPlanId })
      }
    },
    /**
     * @description: 单选和判断题点击
     * @param {Object} 当前项
     * @param {Array} 选项列表
     * @return {Void}
     */
    handleRadio(item, list) {
      if (this.pageType === 'exam') {
        list.forEach((el) => {
          el.u = 0
        })
        item.u = 1
      }
    },
    /**
     * @description: 多选
     * @param {Object} 多选当前项
     * @return {*}
     */
    handleCheckbox(item) {
      if (this.pageType === 'exam') {
        item.u = item.u === 1 ? 0 : 1
      }
    },
    /**
     * @description: 结果
     * @param {Number} type 题目类型
     * @param {Array} list 答案列表
     * @return {String} 结果正确与否
     */
    result(type, list) {
      let text = ''
      switch (type) {
        //单选
        case 0:
          text = list.find((el) => el.u === 1)?.a === 1 ? '正确' : '错误'
          break
        //多项
        case 1:
          const a = list.filter((el) => el.a === 1).map((el) => el.o)
          const u = list.filter((el) => el.u === 1).map((el) => el.o)
          text = JSON.stringify(a) == JSON.stringify(u) ? '正确' : '错误'
          break
        //判断题
        case 2:
          text = list.find((el) => el.u === 1)?.a === 1 ? '正确' : '错误'
          break
      }
      return text
    },
    /**
     * @description: 获取正确答案
     * @param {Number} type 题目类型
     * @param {Array} list 答案列表
     * @return {String} 正确答案
     */
    rightAnswers(type, list) {
      let text = ''
      switch (type) {
        //单选
        case 0:
          text = list.find((el) => el.a === 1).o
          break
        //多项
        case 1:
          text = list
            .filter((el) => el.a === 1)
            .map((el) => el.o)
            .join('、')
          break
        //判断题
        case 2:
          text = list.find((el) => el.a === 1).c
          break
      }
      return text
    },
    /**
     * @description: 多行文本输入
     * @param {Event} e 事件对象
     * @param {Array} i  问答题列表
     * @param {Number} i  问答题索引
     * @return {Void}
     */
    handleTextarea(e, i, index2) {
      i[index2].w = e.target.value
    },
    /**
     * @description: 保存草稿，提交
     * @param {String} type 按钮类型
     * @return {Void}
     */
    handleSubmit(type) {
      if (this.isRequired()) {
        this.form.content.forEach((el1) => {
          if (el1.t === 3) {
            el1.i.forEach((el) => {
              if (el.w) {
                el.w = el.w.replace(/{|}|[|]|/g, '')
                el.w = el.w.replace(/:/g, '：')
                el.w = el.w.replace(/,/g, '，')
                el.w = el.w.replace(/"/g, '“')
              }
            })
          }
        })
        switch (type) {
          case 'DRAFT':
            this.loadingState[type] = true
            saveUserPaperDraft({
              examPlanId: this.$route.query.examPlanId,
              content: this.form.content
            })
              .then(({ code }) => {
                if (code === this.SUCCESS_CODE) {
                  this.$message.success('保存成功')
                  this.handleClose()
                  return Promise.resolve()
                } else {
                  this.$message.error('保存失败')
                  return Promise.reject()
                }
              })
              .catch((error) => {
                console.log(error)
                return Promise.reject()
              })
              .finally(() => {
                this.loadingState[type] = false
              })
            break
          case 'SUBMITTED':
            this.$confirm({
              title: '温馨提示',
              content: '确定是否提交数据？',
              okText: '确认',
              okType: 'danger',
              cancelText: '取消',
              onOk: () => {
                this.loadingState[type] = true
                submitUserPaper({
                  examPlanId: this.$route.query.examPlanId,
                  content: this.form.content
                })
                  .then(({ code }) => {
                    if (code === this.SUCCESS_CODE) {
                      this.$message.success('提交成功')
                      this.handleClose()
                      return Promise.resolve()
                    } else {
                      this.$message.error('提交失败')
                      return Promise.reject()
                    }
                  })
                  .catch((error) => {
                    console.log(error)
                    return Promise.reject()
                  })
                  .finally(() => {
                    this.loadingState[type] = false
                  })
              }
            })
            break
        }
      } else {
        this.$message.warning('除问答题以外，其余均为必填项')
      }
    },
    /**
     * @description: 考卷非空
     * @param {Void}
     * @return {Boolean} 是否非空
     */
    isRequired() {
      let is = true
      const c = this.form.content
      for (let ii = 0; ii < c.length; ii++) {
        if (c[ii].t < 3) {
          for (let jj = 0; jj < c[ii].i.length; jj++) {
            const n = c[ii].i[jj].e.find((el) => el.u === 1)
            if (!n) {
              is = false
              return is
            }
          }
        }
      }
      return is
    },
    /**
     * @description: 关闭
     * @param {Void}
     * @return {Void}
     */
    handleClose() {
      this.$close()
    }
  }
}
</script>
<style lang="less" scoped>
.paper-answer-list {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 1em;
}
.paper-answer-item {
  display: flex;
  width: 25%;
}
.paper-answer-item-wrapper {
  margin-left: 5px;
  display: flex;
  padding-right: 20px;
  cursor: pointer;
  b {
    font-weight: normal;
    margin: 0 5px;
  }
}
.paper-result {
  color: #ec808d;
}
.paper-answer-textarea {
  margin-bottom: 1em;
}
</style>
